package com.jsftoolkit.ajax;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.FacesEvent;

import org.apache.myfaces.trinidad.context.RequestContext;

import com.jsftoolkit.utils.Utils;

/**
 * Hook implementations for Trinidad. See the documentation for
 * {@link AjaxContext} and the Trinidad documenation.
 * 
 * @author noah
 * 
 */
public class TrinidadAjaxContext extends AjaxContext {

	public TrinidadAjaxContext(FacesContext context) {
		this();
	}

	public TrinidadAjaxContext() {
		super();
	}

	@Override
	public boolean isAjaxRequest(FacesContext context) {
		return getRequestContext().isPartialRequest(context);
	}

	@Override
	public void addComponents(UIComponent... components) {
		super.addComponents(components);

		for (UIComponent component : components) {
			if (component != null) {
				getRequestContext().addPartialTarget(component);
			}
		}
	}

	@Override
	public void decode(FacesContext context, UIComponent component) {
		super.decode(context, component);

		// translate partial triggers into a string array
		Object value = component.getAttributes().get("partialTriggers");
		String[] triggers;
		if (value instanceof String[]) {
			triggers = (String[]) value;
		} else if (value instanceof String) {
			triggers = value.toString().split("\\w+");
		} else {
			triggers = Utils.toStringArray(Utils.getIterator(value));
		}
		getRequestContext().addPartialTriggerListeners(component, triggers);
	}

	@Override
	public void broadcast(UIComponent component, FacesEvent event) {
		super.broadcast(component, event);

		UIComponent source = event.getComponent();
		if (source != null) {
			getRequestContext().partialUpdateNotify(source);
		}
	}

	public RequestContext getRequestContext() {
		return RequestContext.getCurrentInstance();
	}

}
